# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.

from odoo import SUPERUSER_ID, api, _
from odoo import registry as registry_get
from ..controllers import mqtt
import json
import logging
_logger = logging.getLogger(__name__)


# from odoo import models, fields


class IotMqttInterface(object):
    def __init__(self, db, model):
        super(IotMqttInterface, self).__init__()
        config = {
            'client_id': 'odoo,' + db,
            'userdata': {'db': db, 'model': model},
        }
        self.controller = mqtt.create_interface(config)

    # def __getattr__(self, name):
    #     print ("__getattr__ called:", name )
    #     if( name[0:11] == 'on_message_'):
    #         return self.on_message
    #     else:
    #         print ("__getattr__ called:", name , ' no method')
    #         pass

    def publish(self, *args, **kwargs):
        print('IotMqttInterface, publish', args, kwargs)
        topic = '/'.join(['down' ] + list(args) )
        self.controller.push_task('publish',  topic, kwargs, qos=2)


    def subscribe(self):
        self.controller.client.message_callback_add('up/#', self.on_message)
        self.controller.push_task('subscribe', 'up/#', qos=2)

    def on_message(self, client, userdata, msg):
        print(' my default, on_message, userdata,', userdata)
        print("Message: " + msg.topic + " " + str(msg.payload))

        topic_split = msg.topic.split('/')
        print("Message: " , topic_split)

        db = userdata.get('db')
        model = userdata.get('model')
        args = topic_split[1:]
        kwargs = msg.payload.decode()
        kwargs = json.loads(kwargs)

        registry = registry_get(db)
        context = {}
        with registry.cursor() as cr:
            api.Environment.reset()
            env = api.Environment(cr, SUPERUSER_ID, context)
            obj = env[model]
            obj.on_message( *args, **kwargs )

